package com.springboot.base.springbootes.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot.base.springbootes.elasticsearch.ElasticSearchConfig;
import com.springboot.base.springbootes.mapper.HotelMapper;
import com.springboot.base.springbootes.pojo.Hotel;
import com.springboot.base.springbootes.pojo.PageResult;
import com.springboot.base.springbootes.pojo.RequestParams;
import com.springboot.base.springbootes.service.HotelService;
import com.springboot.base.springbootes.utils.EsResponseUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: 船长
 * @create: 2025-02-17 19:47
 **/
@Service
public class HotelServiceImpl extends ServiceImpl<HotelMapper, Hotel> implements HotelService {

    @Autowired
    private ElasticSearchConfig elasticSearchConfig;

    @Override
    public PageResult search(RequestParams params) {

        try {
            // 1. 准备request
            SearchRequest request = new SearchRequest("hotel");
            buildBasicQuery(params, request);
            // 分页
            Integer page = params.getPage();
            Integer size = params.getSize();
            request.source().from((page - 1) * size).size(size);

            // 排序功能
            String location = params.getLocation();
            if (location != null && location.equals("")){
                request.source().sort(SortBuilders
                        .geoDistanceSort("location", new GeoPoint(location))
                        .order(SortOrder.ASC)
                        .unit(DistanceUnit.KILOMETERS));
            }


            SearchResponse response = elasticSearchConfig.restHighLevelClient().search(request, RequestOptions.DEFAULT);
            // 4. 解析相应
            return new EsResponseUtil().handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    // 聚合查询
    @Override
    public Map<String, List<String>> filters(RequestParams params) throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        buildBasicQuery(params, request);
        request.source().size(0);
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("cityAgg")
                .field("city")
                .size(20)
        );
        request.source().aggregation(AggregationBuilders
                .terms("starAgg")
                .field("starName")
                .size(20)
        );
        SearchResponse response = elasticSearchConfig.restHighLevelClient().search(request, RequestOptions.DEFAULT);
        // 解析结果
        Aggregations aggregations = response.getAggregations();
        HashMap<String, List<String>> map = new HashMap<>();
        ArrayList<String> brandList = getAggByName(aggregations,"brandAgg");
        ArrayList<String> cityList = getAggByName(aggregations,"cityAgg");
        ArrayList<String> startList = getAggByName(aggregations,"starAgg");
        map.put("brand", brandList);
        map.put("city", cityList);
        map.put("starName", startList);
        System.out.println("map:"+ map);
        return map;
    }

    @Override
    public List<String> suggestion(String prefix) throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        request.source().suggest(new SuggestBuilder().addSuggestion(
                "suggestions",
                SuggestBuilders.completionSuggestion("suggestion")
                        .prefix(prefix)
                        .skipDuplicates(true)
                        .size(10)
        ));
        SearchResponse response = elasticSearchConfig.restHighLevelClient().search(request, RequestOptions.DEFAULT);
        // 解析结果
        Suggest suggest = response.getSuggest();
        CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
        List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
        ArrayList<String> list = new ArrayList<>();
        for (CompletionSuggestion.Entry.Option option : options) {
            String text = option.getText().string();
            list.add(text);
        }
        return list;
    }

    private static ArrayList<String> getAggByName(Aggregations aggregations,String name) {
        Terms brandterms = aggregations.get(name);
        List<? extends Terms.Bucket> buckets = brandterms.getBuckets();
        ArrayList<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            brandList.add(key);
//            System.out.println(key);
        }
        return brandList;
    }

    private static void buildBasicQuery(RequestParams params, SearchRequest request) {
        // 2. 准DSL
        // 2.1 准备reques
        // 构建BooleanQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 关键字搜索
        String key = params.getKey();
        if (key == null || "".equals(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        // 城市条件
        if (params.getCity() != null && !params.getCity().isEmpty()) {
            boolQuery.filter(QueryBuilders.termQuery("city", params.getCity()));
        }
        // 品牌条件
        if (params.getBrand() != null && !params.getBrand().isEmpty()) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        if (params.getStarName() != null && !params.getStarName().isEmpty()) {
            boolQuery.filter(QueryBuilders.termQuery("starName", params.getStarName()));
        }
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders
                    .rangeQuery("price")
                    .gte(params.getMinPrice())
                    .lte(params.getMaxPrice()));
        }

        // 算分控制
        FunctionScoreQueryBuilder functionScoreQueryBuilder =
                QueryBuilders.functionScoreQuery(
                        // 原始查询
                        boolQuery,
                        // function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        // 其中的一个function score 元素
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                // 过滤条件
                                QueryBuilders.termQuery("isAD", true),
                                // 算分函数
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                });


        request.source().query(functionScoreQueryBuilder);
    }


}
